import Vue from 'vue'
import VueRouter from 'vue-router'
import {getCookie} from "@/utils/CookieUtils";
import {message} from "@/utils/age";

const home = () =>
  import("../views/Home")

const welcome = () =>
  import("../components/HelloWorld")

const login = () =>
  import("../components/Login")
const forget = () =>
  import("../components/Forget")
const userHome = () =>
  import("../components/home/UserHome")
const change = () =>
  import("../components/home/Change")
const check = () =>
  import("../components/home/UserNotice")
const repair = () =>
  import("../components/home/Repair")
const cost = () =>
  import("../components/home/Cost")
const lost = () =>
  import("../components/home/Lost")
const root = () =>
  import("../components/root/Root")
const floor = () =>
  import("../components/root/Floor")
const error = () =>
  import("../components/Error")
const test = () =>
  import("../components/Test")


Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home',
  }, {
    path: '/home',
    redirect: '/home/welcome',
    component: home,
    children: [{
      path: 'welcome',
      component: welcome
    }, {
      path: 'userHome',
      component: userHome
    }, {
      path: 'change',
      component: change
    }, {
      path: 'check',
      component: check
    }, {
      path: 'repair',
      component: repair
    }, {
      path: 'cost',
      component: cost
    }, {
      path: 'lost',
      component: lost
    }, {
      path: 'root',
      component: root,
    }]
  }, {
    path: '/login',
    component: login
  }, {
    path: '/forget',
    component: forget
  }, {
    path: '/test',
    component: test
  }, {
    path: '/*',
    component: error
  }]

const router = new VueRouter({
  routes
})

// 解决多次点击push 终端报错
const routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error => error);
};
// router.afterEach((to, from) => {
//   // 跳转之后返回顶部
//   document.documentElement.scrollTop = 0
// })

// 路由白名单
const routerList = ['/login', '/forget', '/home/welcome']

// 路由防卫导航
router.beforeEach((to, from, next) => {

  const token = getCookie("token")
  if (token) {
    if (to.path == '/login') {
      message("warning", "你已经成功登录，请勿反复登录。")
      next("/home/welcome")
    } else {
      next()
    }
  } else {
    if (routerList.includes(to.path)) {
      next()
    } else {
      message("error", "你还未登录，请先去登录！。")
      next('/home/welcome')
    }
  }
})

export default router
